//
//  WZAddScheduleController.m
//  WZEfengAndEtong
//
//  Created by wanzhao on 16/6/13.
//  Copyright © 2016年 wanzhao. All rights reserved.
//

#import "WZAddScheduleController.h"
#import "DateHelper.h"
#import "NSDate+CalculateDay.h"
#import "KMDatePicker.h"
#import "WZRemindController.h"
#import "WZAddSchedule.h"
#import "WZDayPlan.h"
#import "WZDetailSchedule.h"
#import "LocationNotification.h"

#define LocalNotification_ScheduleTitle_KEY @"scheduleTitle"
#define LocalNotification_ScheduleStartTime_KEY @"scheduleStartTime"
#define LocalNotification_ScheduleStartDate_KEY @"scheduleStartDate"


@interface WZAddScheduleController ()<KMDatePickerDelegate, UITextFieldDelegate>

@property (weak, nonatomic) IBOutlet UITableViewCell *remindView;

@property (weak, nonatomic) IBOutlet UITextField *scheduleTitleTF;

@property (weak, nonatomic) IBOutlet UITextField *dateTF;

@property (weak, nonatomic) IBOutlet UITextField *timeTF;

@property (weak, nonatomic) IBOutlet UILabel *remindLabel;

@property (weak, nonatomic) IBOutlet UISwitch *remindSW;

@property (nonatomic, strong) NSMutableArray *addScheduleArr;

@property (nonatomic, copy) NSString *saveScheduleID;

@property (nonatomic, weak) UIView *cover;

/**提醒时间长*/
@property (nonatomic, copy) NSString *beforeLength;
/**提醒单位*/
@property (nonatomic, copy) NSString *beforeUnitName;
/**提醒标记*/
@property (nonatomic, copy) NSString *alertFlag;
@property (nonatomic, copy) NSString *reserved1;
@property (nonatomic, copy) NSString *reserved2;

@property (nonatomic, assign) NSInteger badgeNumber;


@end

@implementation WZAddScheduleController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setupTableView];
    
    [self layoutUI];
    
}

- (void)setupTableView {
    
    self.view.backgroundColor = RGBCOLORWITH16COLOR(0xf5f5f5);
    self.navigationItem.title = @"新建日程";
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem BarButtonItemWithImageName:nil title:@"保存" target:self sel:@selector(saveScheduleBtnDidClick) titleFont:Font17 titleColor:WhiteColor];
    self.navigationItem.rightBarButtonItem.enabled = NO;
    self.tableView.tableFooterView = [[UIView alloc] init];
    
    self.scheduleTitleTF.delegate = self;
    
    /**初始化控件*/
    NSString *currentDate = [NSDate getTimeDateWithDateFormatter:@"yyyy-MM-dd"];
    NSString *currentTime = [NSDate getTimeDateWithDateFormatter:@"HH:mm"];
    self.dateTF.text = currentDate;
    self.timeTF.text = currentTime;
    
    self.tableView.showsVerticalScrollIndicator = NO;
    self.tableView.showsHorizontalScrollIndicator = NO;
    
    self.beforeUnitName = @"分钟";
    self.beforeLength = @"15";
    self.alertFlag = @"2";
}

- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:YES];
    
    [_scheduleTitleTF addTarget:self action:@selector(textChanged) forControlEvents:UIControlEventEditingChanged];
//    self.navigationItem.rightBarButtonItem.enabled = NO;
}

- (void)textChanged {
    
    self.navigationItem.rightBarButtonItem.enabled = _scheduleTitleTF.text.length;
}

- (void)viewDidAppear:(BOOL)animated {
    
    [super viewDidAppear:animated];
    
    [_scheduleTitleTF becomeFirstResponder];
}


- (IBAction)remindSwitch:(UISwitch *)sender {
    
    if (!sender.isOn) {
        
        self.remindView.hidden = YES;
        
    } else {
        
        self.remindView.hidden = NO;
    }
    
//    NSIndexPath *index = [NSIndexPath indexPathForRow:1 inSection:2];
//    
//    [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:index, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
    
//    NSIndexSet *indexSet = [[NSIndexSet alloc] initWithIndex:2];
//    [self.tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationAutomatic];
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
//    WZLog(@"section = %lu, row = %lu", indexPath.section, indexPath.row);
    
    if (2 == indexPath.section && 1 == indexPath.row) {
        
        WZRemindController *remindVC = [[WZRemindController alloc] init];
        
        // 接收提醒时间
        remindVC.addVcBlock = ^(NSString *alertFlag, NSString *beforeLength, NSString *unitName){
            
            self.alertFlag = alertFlag;
            self.beforeLength = beforeLength;
            self.beforeUnitName = unitName;
            
            if ([alertFlag isEqualToString:@"2"]) {
                
                // 提醒 打开
                self.remindSW.on = YES;
                self.remindLabel.text = [NSString stringWithFormat:@"提前%@%@",beforeLength, unitName];
                
            } else {
                
                // 不提醒 关闭
                self.remindSW.on = NO;
                self.remindLabel.text = @"不提前提醒";
            }
            
            [tableView reloadData];
        };
        
        [self.navigationController pushViewController:remindVC animated:YES];
    }
}

/**日期时间选择*/

- (IBAction)dateSelectBtnDidClick:(UIButton *)sender {
    
    CGRect rect = CGRectMake(0.0, 0.0, 0, 0);
    UIView *cover = [[UIView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    self.cover = cover;
    cover.backgroundColor = [UIColor colorWithRed:0/255.0f green:0/255.0f blue:0/255.0f alpha:102/255.0];
    [self.tableView addSubview:cover];
    // 年月日
    KMDatePicker *datePicker = [[KMDatePicker alloc]
                                initWithFrame:rect
                                delegate:self
                                datePickerStyle:KMDatePickerStyleYearMonthDay];
    
    [self.cover addSubview:datePicker];
    
    [datePicker mas_makeConstraints:^(MASConstraintMaker *make) {
        //            make.right.equalTo(self.view.mas_right).offset(-30);
        //            make.left.equalTo(self.view.mas_left).offset(30);
        make.centerX.equalTo(self.view.mas_centerX);
        make.centerY.equalTo(self.view.mas_centerY);
        make.size.mas_equalTo(CGSizeMake(240, 186));
    }];
    
    UILabel *yearLabel = [[UILabel alloc] init];
    yearLabel.text = @"选择年月日";
    [yearLabel sizeToFit];
    
    [datePicker addSubview:yearLabel];
    [yearLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(datePicker.mas_top).offset(9);
        make.centerX.equalTo(datePicker.mas_centerX);
    }];
    
    // 年月日时分；限制时间范围
    datePicker = [[KMDatePicker alloc]
                  initWithFrame:rect
                  delegate:self
                  datePickerStyle:KMDatePickerStyleYearMonthDayHourMinute];
    datePicker.minLimitedDate = [[DateHelper localeDate] addMonthAndDay:-24 days:0];
    datePicker.maxLimitedDate = [datePicker.minLimitedDate addMonthAndDay:48 days:0];
    
}


- (IBAction)timeBtnDidClick:(UIButton *)sender {
    
    CGRect rect = CGRectMake(0.0, 0.0, 0, 0);
    UIView *cover = [[UIView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    self.cover = cover;
    cover.backgroundColor = [UIColor colorWithRed:0/255.0f green:0/255.0f blue:0/255.0f alpha:102/255.0];
    [self.tableView addSubview:cover];

    // 时分
    KMDatePicker *datePicker = [[KMDatePicker alloc]
                                initWithFrame:rect
                                delegate:self
                                datePickerStyle:KMDatePickerStyleHourMinute];
    
    [self.cover addSubview:datePicker];
    
    [datePicker mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.right.equalTo(self.view.mas_right).offset(-30);
//        make.left.equalTo(self.view.mas_left).offset(30);
        make.centerX.equalTo(self.view.mas_centerX);
        make.centerY.equalTo(self.view.mas_centerY);
        make.size.mas_equalTo(CGSizeMake(240, 186));
    }];

    UILabel *timeLabel = [[UILabel alloc] init];
    timeLabel.text = @"选择时间";
    [timeLabel sizeToFit];
    
    [datePicker addSubview:timeLabel];
    [timeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(datePicker.mas_top).offset(8);
        make.centerX.equalTo(datePicker.mas_centerX);
    }];
    
    // 年月日时分；限制时间范围
    datePicker = [[KMDatePicker alloc]
                  initWithFrame:rect
                  delegate:self
                  datePickerStyle:KMDatePickerStyleYearMonthDayHourMinute];
    datePicker.minLimitedDate = [[DateHelper localeDate] addMonthAndDay:-24 days:0];
    datePicker.maxLimitedDate = [datePicker.minLimitedDate addMonthAndDay:48 days:0];
}

- (void)layoutUI {
    CGRect rect = [[UIScreen mainScreen] bounds];
    rect = CGRectMake(0.0, 0.0, rect.size.width, 216.0);
    
    // 年月日
    KMDatePicker *datePicker = [[KMDatePicker alloc]
                  initWithFrame:rect
                  delegate:self
                  datePickerStyle:KMDatePickerStyleYearMonthDay];
    
    self.dateTF.delegate = self;
    self.dateTF.inputView = datePicker;
    
    // 时分
    datePicker = [[KMDatePicker alloc]
              initWithFrame:rect
              delegate:self
              datePickerStyle:KMDatePickerStyleHourMinute];

    self.timeTF.delegate = self;
    self.timeTF.inputView = datePicker;

    // 年月日时分；限制时间范围
    datePicker = [[KMDatePicker alloc]
              initWithFrame:rect
              delegate:self
              datePickerStyle:KMDatePickerStyleYearMonthDayHourMinute];
    datePicker.minLimitedDate = [[DateHelper localeDate] addMonthAndDay:-24 days:0];
    datePicker.maxLimitedDate = [datePicker.minLimitedDate addMonthAndDay:48 days:0];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    
    [self.view resignFirstResponder];
    [super touchesBegan:touches withEvent:event];
}



#pragma mark - UITextFieldDelegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    
    [textField resignFirstResponder];
    return YES;
}


#pragma mark - KMDatePickerDelegate
- (void)datePicker:(KMDatePicker *)datePicker didSelectDate:(KMDatePickerDateModel *)datePickerDate {
    
    if (datePicker.datePickerStyle == 1) {
        
      NSString *dateStr = [NSString stringWithFormat:@"%@-%@-%@", datePickerDate.year,datePickerDate.month,datePickerDate.day];
        
        self.dateTF.text = dateStr;
   }
    
    if (datePicker.datePickerStyle == 3){
      NSString *timerStr = [NSString stringWithFormat:@"%@:%@",datePickerDate.hour,datePickerDate.minute];
        
        self.timeTF.text = timerStr;
    }
    
}

#pragma mark - 保存日程按钮点击

- (void)saveScheduleBtnDidClick {
    
    NSString *str = [self.dateTF.text stringByAppendingFormat:@" %@", self.timeTF.text];
    NSString *startTime = [NSDate cTimestampStringFromString:str format:@"yyyy-MM-dd HH:mm"];
    NSString *alertFlag = self.remindSW.on ? @"2" : @"1"; // 1不提醒
//    NSString *beforeUnitName = self.beforeUnitName;
    NSString *beforeUnitFlag = @""; // 分钟, 小时, 天
    NSString *editFlag = @"1"; // 增加日程
    NSString *alertTime = nil;
    
    if ([alertFlag isEqualToString:@"2"]) {
        
        if ([self.beforeUnitName isEqualToString:@"分钟"]) {
            // 分钟转化秒
            NSTimeInterval alertSecond = [self.beforeLength longLongValue] * 60 * 1000;
            NSTimeInterval alert = [startTime longLongValue] - alertSecond;
            alertTime = [NSString stringWithFormat:@"%f", alert];
            beforeUnitFlag = @"1";
            
        }
        
        if ([self.beforeUnitName isEqualToString:@"小时"]) {
            // 小时转化秒
            NSTimeInterval alertSecond = [self.beforeLength longLongValue] * 60 * 60 * 1000;
            NSTimeInterval alert = [startTime intValue] - alertSecond;
            alertTime = [NSString stringWithFormat:@"%f", alert];
            beforeUnitFlag = @"2";
        }
        
        if ([self.beforeUnitName isEqualToString:@"天"]) {
            // 天转化秒
            NSTimeInterval alertSecond = [self.beforeLength longLongValue] * 24 * 60 * 60 * 1000;
            NSTimeInterval alert = [startTime intValue] - alertSecond;
            alertTime = [NSString stringWithFormat:@"%f", alert];
            beforeUnitFlag = @"3";
        }
        
    } else {
        
        alertTime = @"0";
    }
    
    [NetWorkShare saveScheduleWithUserName:self.oaUserName pwd:self.oaPwd scheduleID:nil scheduleTitle:self.scheduleTitleTF.text startTime:startTime alertTime:alertTime alertFlag:alertFlag beforeLength:self.beforeLength beforeUnitFlag:beforeUnitFlag editFlag:editFlag successHandle:^(AFHTTPRequestOperation *operation, id responseObject) {
        if (responseObject) {
            
            if ([[responseObject objectForKey:@"success"] boolValue]) {
                
                if ([alertFlag isEqualToString:@"2"] && ![self.remindLabel.text isEqualToString:@"不提前提醒"] && ![alertTime isEqualToString:@"0"]) {
                    
                    NSTimeInterval localNotifyTime = [alertTime longLongValue] / 1000;
                    NSDate *fireDate = [NSDate dateWithTimeIntervalSince1970:localNotifyTime];
                    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
                    [dict setObject:_scheduleTitleTF.text forKey:LocalNotification_ScheduleTitle_KEY];
                    [dict setObject:_timeTF.text forKey:LocalNotification_ScheduleStartTime_KEY];
                    [dict setObject:_dateTF.text forKey:LocalNotification_ScheduleStartDate_KEY];
                    
                    [LocationNotification registerLocalNotificationWithFireDate:fireDate repeatType:NSCalendarUnitMinute entity:dict.copy];
                    
                }
                
                [MBProgressHUD showSuccess:@"保存日程成功"];
                self.saveScheduleID = responseObject[@"id"];
                
                // 属性包装为模型传递
                WZDayPlan *newSchedule = [WZDayPlan dayPanWithTitlt:self.scheduleTitleTF.text scheduleID:self.saveScheduleID startTime:self.dateTF.text alertFlag:@"1" alertTime:alertTime beforeLength:_beforeLength beforeUnitFlag:@"1"];
                
                if (_block) {
                    _block(newSchedule);
                }
                
                
                WZLog(@"保存成功");
                
                [self.navigationController popViewControllerAnimated:YES];
                
            } else {
                
                [MBProgressHUD showError:[responseObject objectForKey:@"message"]];
            }
        } else {
            [MBProgressHUD showError:UNKNOWNERROR];
        }
        
        WZLog(@"%@", self.scheduleTitleTF.text);
        WZLog(@"result = %@", responseObject);
//        WZLog(@"保存成功");
    } failureHandle:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        [MBProgressHUD showError:NETWORKNERROR];
        WZLog(@"error = %@", error);
    }];
  
    /*
    // 通过代理传值
    if ([_delegate respondsToSelector:@selector(addScheduleController:didSaveButtonWith:)]) {
        
        [_delegate addScheduleController:self didSaveButtonWith:newSchedule];
    }*/

}


- (void)applicationLocalNotificationWithFireDate:(NSTimeInterval)localNotifyTime {
    
    [[UIApplication sharedApplication] cancelAllLocalNotifications];
    
    UILocalNotification *localNotif = [[UILocalNotification alloc] init];
    localNotif.fireDate = [NSDate dateWithTimeIntervalSince1970:localNotifyTime];
//    localNotif.repeatInterval = NSCalendarUnitMinute;
    
    [self setupLocalNotificationWithLocalNotif:localNotif
                                     alertBody:@"测试本地推送"
                                    alertTitle:@"测试"
                                   alertAction:@"打开"];
    
    localNotif.applicationIconBadgeNumber = 1;
    
    // 在指定的日期触发消息
    [[UIApplication sharedApplication] scheduleLocalNotification:localNotif];
    
//    [[UIApplication sharedApplication] presentLocalNotificationNow:localNotif]; // 立即触发通知
}

- (void)setupLocalNotificationWithLocalNotif:(UILocalNotification *)localNotif alertBody:(NSString *)alertBody alertTitle:(NSString *)alertTitle alertAction:(NSString *)alertAction {
    
    localNotif.soundName = UILocalNotificationDefaultSoundName;
    localNotif.alertAction = alertAction;
    localNotif.alertTitle = alertTitle;
    localNotif.alertBody = alertBody;
}

// 处理网络请求参数
- (void)detailNetworkPamarm {
    

}

// 懒加载
- (NSMutableArray *)AddScheduleArr:(NSMutableArray *)addScheduleArr {
    
    if (_addScheduleArr == nil) {
        _addScheduleArr = [NSMutableArray array];
    }
    return _addScheduleArr;
}


@end
